<template>
  <div class="update-contianer">
    <img id="image" :src="ImageData" />
    <div class="btns-bar">
      <van-button type="default" class="cancel btn" @click="$emit('close')"
        >取消</van-button
      >
      <van-button type="default" class="submit btn" @click="updateimg()"
        >提交</van-button
      >
    </div>
  </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  props: {
    ImageData: {
      type: [String, Object],
      require: true
    }
  },
  // 定义属性
  data() {
    return {
      cropper: null
    }
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    updateimg() {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message: '保存中'
        })
        try {
          // 封装文件上传的参数
          const formdata = new FormData() // 新建formdata对象
          formdata.append('photo', blob) // 追加参数，参数名+值
          const { data } = await updateUserPhoto(formdata) // 发送修改图片请求
          console.log(data)
          this.$emit('close') //关闭弹出层
          this.$emit('updateimg', data.data.photo) // 传给父组件
          this.$toast.success('保存成功')
        } catch (err) {
          console.log(err)
          this.$toast.success('保存失败')
        }
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    const image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: true,
      cropBoxResizable: true,
      background: false,
      movable: true
    })
  }
}
</script>

<style lang="less">
.update-contianer {
  background-color: #000;
  /* Ensure the size of the image fit the container perfectly */
  #img {
    display: block;

    /* This rule is very important, please don't ignore this */
    max-width: 100%;
  }
  .btns-bar {
    position: absolute;
    bottom: 50px;
    height: 80px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 30px;
  }
}
</style>
